/**
 Copyright (C) 2013 Yuyao Liang

 This source code is release under the BSD License.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.

 Created on Oct 23, 2013 4:12:16 PM
 */
package com.google.srclib.stock;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.google.srclib.dataset.SimpleResultSet;
import com.google.srclib.dataset.StockRecordDataset;
import com.google.srclib.io.zip.Zipper;

/**
 * @author lianyuy
 * 
 */
public class StockDataUpdater {
	private static final int NTHREDS = 10;

	public static void updateStockData(String stocksymbolfilename,
			String[] exchangenames) {
		try {
			String[] stockfilenames = getstockfilenames(exchangenames);
			updateStockDataset(stocksymbolfilename, stockfilenames);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param names
	 * @return
	 */
	private static String[] getstockfilenames(String[] names) {
		String[] filenames = new String[names.length];
		for (int i = 0; i < names.length; i++) {
			filenames[i] = names[i] + "Stocks.zip";
		}
		return filenames;
	}

	private static void updateStockDataset(String symbolfile, String[] stockfile)
			throws SQLException, IOException {
		String backup_stockfilename = stockfile + ".old";
		String[] names = StockCodeCollector.ExchangeNames;

		Zipper zipper = Zipper.getInstance();
		int index = 0;
		for (String name : names) {
			ZipInputStream zin = zipper.getZipFile(symbolfile);
			SimpleResultSet srs = (SimpleResultSet) zipper.csvReader(zin, name
					+ ".csv");
			zin.close();
			zin = null;

			if (srs != null) {
				StockSymbolDataSet ss = new StockSymbolDataSet(srs);
				System.out.println(name + "    " + ss.getCount());

				File orign_stockfile = new File(stockfile[index]);
				boolean exists = (orign_stockfile).exists();
				if (exists) {
					File backup_stockfile = new File(backup_stockfilename);
					orign_stockfile.renameTo(backup_stockfile);
				}
				File backup_stockfile = new File(backup_stockfilename);
				exists = backup_stockfile.exists();
				if (exists) {
					zin = zipper.getZipFile(backup_stockfilename);
				}

				ZipOutputStream zout = zipper.makeZipFile(stockfile[index++]);
				try {
					ExecutorService executor = Executors
							.newFixedThreadPool(NTHREDS);
					while (ss.next()) {
						String stock = ss.getString(1);

						StockRecordDataset sd = new StockRecordDataset(stock);
						if (zin != null) {
							srs = (SimpleResultSet) zipper.csvReader(zin, stock
									+ ".csv");
							if (srs != null)
								sd = new StockRecordDataset(srs);
						}

						Callable<StockRecordDataset> worker = new StockDatasetUpdater(
								stock, sd);
						Future<StockRecordDataset> submit = executor
								.submit(worker);
						if (submit != null) {
							sd = submit.get();
							zipper.csvWriter(zout, sd, stock + ".csv");
							System.out
									.println(stock + "      " + sd.getCount());
						}
					}
					executor.shutdown();
					while (!executor.isTerminated()) {
						// waiting
					}
					if (exists) {
						zin.close();
						backup_stockfile.delete();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				zout.close();
			}
		}
	}

}
